package com.my.lock.v25;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * Created by ZhongGang
 * at 2018/9/14 11:36
 */
public class ReentrantFairLock implements Lock {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReentrantFairLock.class);

    private Sync sync = new Sync();

    @Override
    public void lock() {
        this.sync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        this.sync.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return this.sync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return this.sync.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        this.sync.release(1);
    }

    @Override
    public Condition newCondition() {
        throw new UnsupportedOperationException("Not yet implemented!");
    }

    private static class Sync extends AbstractQueuedSynchronizer {

        @Override
        protected boolean tryAcquire(int arg) {
            Thread currentThread = Thread.currentThread();
            if (hasQueuedPredecessors()) {
                return false;
            }

            if (this.compareAndSetState(0, 1)) {

                Collection<Thread> queuedThreads = this.getQueuedThreads();
                for (Thread queuedThread : queuedThreads) {
                    LOGGER.info("queued: {}", queuedThread.getName());
                }

                this.setExclusiveOwnerThread(currentThread);
                return true;
            } else {
                if (currentThread == this.getExclusiveOwnerThread()) {
                    int state = getState();
                    this.setState(++state);
                    return true;
                }
                return false;
            }
        }

        @Override
        protected boolean tryRelease(int arg) {
            int state = getState();
            state -= 1;
            if (state == 0) {
                this.setState(0);
                this.setExclusiveOwnerThread(null);
                return true;
            }
            return false;
        }

        @Override
        protected boolean isHeldExclusively() {
            return Thread.currentThread() == getExclusiveOwnerThread();
        }
    }


    public static void main(String[] args) {
        ReentrantFairLock lock = new ReentrantFairLock();

        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        lock.lock();
                        Thread.sleep(3000);
                        LOGGER.info("locked by {}", Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        throw new UnsupportedOperationException("Not yet implemented!");
                    } finally {
                        lock.unlock();
                    }
                }
            });
        }
    }
}
